package org.jmetrix.samples.application;

import org.jmetrix.jmx.JmxExposer;
import org.jmetrix.jmx.JmxMonitor;

import javax.management.MBeanServer;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
import java.util.Set;

/**
 * @author Konstantin Kuzmin
 * @version $Revision$
 * @since 21.10.11
 */
public class JmxMonitorSample {
    public static final OrderManager orderManager = new OrderManager();
    private static final long EXPOSE_PERIOD = 250;

    public static void main(String[] args) throws Exception {
        // Create and start performance monitor
        JmxMonitor jmxMonitor = new JmxMonitor();
        jmxMonitor.setPeriodMillis(EXPOSE_PERIOD);
        jmxMonitor.start();

        try {
            // Execute some application calls
            orderManager.processOrder(new InternalOrder(50));
            orderManager.processOrder(new ExternalOrder(100));

            // Just to make sure that performance metrics has been processed and exposed to JMX (asynchronously)
            Thread.sleep(EXPOSE_PERIOD * 2);

            // Output performance metrics
            System.out.println("Performance metrics: " + jmxMonitor.getMetrixAggregator());

            // Check that the performance mertics are available via JMX
            MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
            Set<ObjectInstance> objectInstances = mBeanServer.queryMBeans(new ObjectName(JmxExposer.DEFAULT_DOMAIN + ":*,name=InternalOrder"), null);
            System.out.println(objectInstances.size());
            System.out.println(mBeanServer.getAttribute(objectInstances.iterator().next().getObjectName(), "Average"));
        } finally {
            // Stop the performance monitor
            jmxMonitor.stop();
        }
    }
}
